<template>
    <n-form
        ref="formRef"
        label-placement="top"
        :label-width="80"
        :model="form"
        :rules="rules"
    >

        <n-form-item label="请输入名称" path="name">
            <n-input v-model:value="form.name" placeholder="" />
        </n-form-item>
        <n-form-item label="匹配类型" path="type">
            <jb-radio-group
                v-model:value="form.type"
                value-to-number
                url="/api/admin/wechatAutoReply/keywords/types"
            ></jb-radio-group>
        </n-form-item>
    </n-form>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import type { FormInst, FormRules } from 'naive-ui'
import { Rules } from '@/utils'
import { JBoltApi } from '@/utils/request'
import { useResetableData } from '@/hooks/common/use-resetable-data'
import { ResData } from '@/typings/request'

const props = withDefaults(
    defineProps<{
        autoReplyId: string
        mpId: string
        id: string
    }>(),
    {
        id: '',
        autoReplyId: '',
        mpId: ''
    }
)

/** 表单相关 start */
const formRef = ref<FormInst | null>()
interface BucketType {
    type: number
    name: string
}
const form = useResetableData<BucketType>({
    type: 1,
    name: ''
})
const rules: FormRules = {
    type: new Rules().required('请选择匹配类型').value,
    name: new Rules().required('请输入名称').value
}
/**
 * 提交表单
 */
async function submit() {
    await formRef.value?.validate()

    let url = props.id ? '/api/admin/wechatAutoReply/keywords/update' : '/api/admin/wechatAutoReply/keywords/save'
    await JBoltApi.tryPost(url,{
        autoReplyId: props.autoReplyId,
        wechatKeywords:{
            mpId: props.mpId,
            type: form.type,
            name: form.name,
            autoReplyId: props.autoReplyId,
            id:props.id
        },
    })
    return true
}

function loadEditData() {
    JBoltApi.get<ResData>(`/api/admin/wechatAutoReply/keywords/${props.autoReplyId}-${props.id}`).then(({ error, result }) => {
        if (error) return
        form._reset(result.data)
    })
}

onMounted(() => {
    if (props.id) {
        loadEditData()
    }
})

defineExpose({
    submit
})

/** 表单相关 end */
</script>
<style scoped></style>
